package com.tacuati.ui;

import java.awt.Insets;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JToolBar;

import com.tacuati.Main;

public class MainToolBar extends JToolBar {
	private static final long serialVersionUID = 1L;

	MainToolBarButton bOpen;
	MainToolBarButton bSave;
	MainToolBarButton bExit;
	MainToolBarButton bHelp;
	
	public MainToolBar(final Main main) {

		setOrientation(JToolBar.HORIZONTAL);
		setFloatable(false);
				
		AbstractAction actionOpen = new AbstractAction() {
			@Override
			public void actionPerformed(ActionEvent e) {
				JFileChooser fileChooser = new JFileChooser();
				fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				fileChooser.setCurrentDirectory(new java.io.File("."));
				fileChooser.setAcceptAllFileFilterUsed(false);

				if (fileChooser.showOpenDialog(main.getContentPane()) == JFileChooser.APPROVE_OPTION) {
					main.setKindleRoot(fileChooser.getSelectedFile().getAbsolutePath());
					main.loadItems();
				}
			}
		};
		bOpen = new MainToolBarButton(new ImageIcon("open.png"), "Open", actionOpen);
		add(bOpen);

		AbstractAction actionSave = new AbstractAction() {
			@Override
			public void actionPerformed(ActionEvent e) {
				main.save();
			}
		};
		bSave = new MainToolBarButton(new ImageIcon("save.png"), "Save", actionSave);
		bSave.setEnabled(false);
		add(bSave);
		
		AbstractAction actionHelp = new AbstractAction() {
			@Override
			public void actionPerformed(ActionEvent e) {
				main.help();
			}
		};
		MainToolBarButton bHelp = new MainToolBarButton(new ImageIcon("help.png"), "Help", actionHelp);
		add(bHelp);

		AbstractAction actionExit = new AbstractAction() {
			@Override
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		};
		bExit = new MainToolBarButton(new ImageIcon("exit.png"), "Exit", actionExit);
		add(bExit);
	}

	protected class MainToolBarButton extends JButton {
		private static final long serialVersionUID = 1L;

		public MainToolBarButton(Icon icon, String text, AbstractAction action) {
			setAction(action);
			setIcon(icon);
			setText(text);
			setMargin(new Insets(0, 0, 0, 0));
			setVerticalTextPosition(BOTTOM);
			setHorizontalTextPosition(CENTER);
		}
	}

	public void enableSave() {
		bSave.setEnabled(true);
	}

	public void disableSave() {
		bSave.setEnabled(false);
	}
}
